#!/usr/bin/env python3

from vosk import Model, KaldiRecognizer
import json
import os

if not os.path.exists("python/api/model"):
    print ("Please download the model from https://alphacephei.com/vosk/models and unpack as 'model' in the current folder.")
    exit (1)


model = Model("python/api/model")

# Large vocabulary free form recognition
rec = KaldiRecognizer(model, 16000)

# You can also specify the possible word list
# rec = KaldiRecognizer(model, 16000, "Collection list set map iterator get new TreeMap HashMap ArrayList LinkedList")

def to_text(file_path: str):
    wf = open(file_path, "rb")
    wf.read(44)  # skip header
    final_result = ""
    while True:
        data = wf.read(4000)
        if len(data) == 0:
            break
        if rec.AcceptWaveform(data):
            res = json.loads(rec.Result())
            final_result += res['text']
    if len(final_result) == 0:
        res = json.loads(rec.FinalResult())
        final_result = res['text']
    return ''.join(final_result.split())


